#include "IOStreamTestFixture.h"
#include "Assert.h"
#include "UserInterface.h"
#include "Timeout.h"

void IOStreamTestFixture::setUp() {
	START_TIMEOUT(1000);
	// redirect tested program output stream and the result stream to one buffer
	this->resultsStreamBuffer = new stringbuf;
	this->resultsStream = new istream(this->resultsStreamBuffer);
	UserInterface::out.rdbuf(this->resultsStreamBuffer);

	// redirect tested program input stream and the stimul stream to one buffer
	this->stimulsStreamBuffer = new stringbuf;
	this->stimulsStream = new ostream(this->stimulsStreamBuffer);
	UserInterface::in.rdbuf(this->stimulsStreamBuffer);
}

void IOStreamTestFixture::tearDown() {
	STOP_TIMEOUT();
	delete this->resultsStream;
	delete this->resultsStreamBuffer;
	delete this->stimulsStream;
	delete this->stimulsStreamBuffer;
}

string IOStreamTestFixture::getResult(const int resultSize) {
	ASSERT(resultSize > 0);
	this->resultsStream->seekg(-resultSize, ios::end); // skip unneeded data
	// read the result
	string result(resultSize, '\0');
	char c;
	unsigned int i = 0;
	while (this->resultsStream->get(c)) {
		result[i] = c;
		i++;
	}
	return result;
}
